<template>
  <div class="distributor-apply-page page-container">
    <!-- 表单内容区域 -->
    <div class="menu-list">
      <div class="menu-section">
        <a-form :form="form" @submit="handleSubmit" class="apply-form">
          <!-- 申请原因 -->
          <div class="form-item">
            <div class="form-label">申请原因</div>
            <a-form-item>
              <a-textarea
                v-decorator="[
                  'reason',
                  {
                    rules: [
                      { required: true, message: '请填写申请原因' },
                      { min: 20, message: '至少填写20个字符' },
                    ],
                  },
                ]"
                placeholder="请详细说明您申请成为分销员的原因和优势"
                :auto-size="{ minRows: 4, maxRows: 6 }"
              />
            </a-form-item>
          </div>

          <!-- 联系方式 -->
          <div class="form-item">
            <div class="form-label">联系电话</div>
            <a-form-item>
              <a-input
                v-decorator="[
                  'contact',
                  {
                    rules: [
                      { required: true, message: '请输入联系电话' },
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号' },
                    ],
                  },
                ]"
                placeholder="请输入您的手机号码"
              />
            </a-form-item>
          </div>

          <!-- 返款方式 -->
          <div class="form-item">
            <div class="form-label">返款方式</div>
            <a-form-item>
              <a-radio-group
                v-decorator="[
                  'paymentMethod',
                  { initialValue: 'qrcode', rules: [{ required: true }] },
                ]"
              >
                <a-radio value="qrcode">
                  <a-icon type="qrcode" />
                  二维码收款
                </a-radio>
                <a-radio value="offline">
                  <a-icon type="transaction" />
                  线下结算
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
        </a-form>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <a-button
          type="primary"
          block
          size="large"
          :loading="submitting"
          @click="handleSubmit"
        >
          提交申请
        </a-button>
      </div>

      <!-- 申请历史 -->
      <div class="menu-section">
        <div class="section-title">申请历史</div>
        <a-table 
          rowKey="id"
          :columns="columns"
          :data-source="historyData"
          :loading="loading"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'createTime'">
              {{ formatTime(record.createTime) }}
            </template>
            <template v-else-if="column.dataIndex === 'refundMethod'">
              {{ getRefundMethodText(record.refundMethod) }}
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { addSaleApplyFor, querySaleApplyForList } from "@/api/saleApplyFor";

export default {
  name: "DistributorApply",
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  data() {
    return {
      submitting: false,
      loading: false,
      historyData: [],
      columns: [
        {
          title: '申请时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 140,
          ellipsis: true
        },
        {
          title: '联系方式',
          dataIndex: 'link',
          key: 'link',
          width: 100,
          ellipsis: true
        },
        {
          title: '返款方式',
          dataIndex: 'refundMethod',
          key: 'refundMethod',
          width: 80,
          ellipsis: true
        },
        {
          title: '申请原因',
          dataIndex: 'reason',
          key: 'reason',
          width: 200,
          ellipsis: true
        }
      ]
    };
  },
  mounted() {
    this.fetchHistory();
  },
  methods: {
    formatTime(time) {
      return new Date(time)
        .toLocaleDateString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
        })
        .replace(/\//g, "-");
    },
    getRefundMethodText(method) {
      const textMap = {
        qrcode: "二维码收款",
        offline: "线下结算",
      };
      return textMap[method] || method;
    },
    async fetchHistory() {
      this.loading = true
      try {
        const response = await querySaleApplyForList({
          userId: this.$store.getters['user/id']
        })
        
        if (response.code === 200) {
          this.historyData = response.data || []
        } else {
          this.$message.error(response.message || '获取申请历史失败')
        }
      } catch (error) {
        console.error('获取申请历史失败:', error)
        this.$message.error('获取申请历史失败')
      } finally {
        this.loading = false
      }
    },
    async handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.submitting = true;
          try {
            const params = {
              userId: this.$store.getters["user/id"],
              link: values.contact,
              refundMethod: values.paymentMethod,
              reason: values.reason,
            };

            const response = await addSaleApplyFor(params);

            if (response.code === 200) {
              this.$notification.success({
                message: "申请提交成功",
                description: "我们将在3个工作日内审核您的申请",
              });
              this.form.resetFields();
              this.fetchHistory(); // 刷新历史记录
            } else {
              this.$message.error(response.message || "申请提交失败");
            }
          } catch (error) {
            console.error("申请提交失败:", error);
            this.$message.error("申请提交失败，请稍后重试");
          } finally {
            this.submitting = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.distributor-apply-page {
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;

  .page-header {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;

      .back-btn {
        padding: 0;
        height: auto;
        font-size: 14px;
        color: #666;

        .anticon {
          font-size: 14px;
          margin-right: 4px;
        }

        &:hover {
          color: #1890ff;
        }
      }

      .divider {
        width: 1px;
        height: 14px;
        background: #e8e8e8;
      }

      .page-title {
        font-size: 14px;
        font-weight: 500;
        color: #262626;
      }
    }
  }

  .menu-section {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;

    .section-title {
      padding: 12px 16px;
      font-size: 14px;
      color: #8c8c8c;
      background: #fafafa;
      border-bottom: 1px solid #f0f0f0;
    }

    .apply-form {
      padding: 0 16px;

      .form-item {
        padding: 16px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .form-label {
          margin-bottom: 8px;
          font-size: 14px;
          color: #262626;
        }

        :deep(.ant-form-item) {
          margin-bottom: 0;
        }

        :deep(.ant-input) {
          border-radius: 4px;
        }

        :deep(.ant-radio-group) {
          display: flex;
          gap: 24px;
        }
      }
    }

    :deep(.ant-table) {
      background: #fff;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .ant-table-thead > tr > th,
      .ant-table-tbody > tr > td {
        padding: 12px 8px !important;
        white-space: nowrap;
      }

      .ant-table-tbody > tr > td {
        &:nth-child(4) { // 申请原因列
          white-space: normal;
          word-break: break-all;
        }
      }
    }
  }

  .submit-section {
    margin-top: 24px;
    padding: 0 16px;
    margin-bottom: 12px;
    .ant-btn {
      height: 44px;
      font-size: 16px;
      border-radius: 8px;
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .distributor-apply-page {
    padding: 12px;

    .page-header {
      padding: 12px 16px;

      .header-left {
        gap: 6px;

        .back-btn {
          font-size: 13px;

          .anticon {
            font-size: 13px;
          }
        }

        .divider {
          height: 12px;
        }

        .page-title {
          font-size: 13px;
        }
      }
    }

    .menu-section {
      .apply-form {
        .form-item {
          padding: 12px 0;

          .form-label {
            font-size: 13px;
          }
        }
      }

      :deep(.ant-table) {
        font-size: 12px;
        
        .ant-table-thead > tr > th,
        .ant-table-tbody > tr > td {
          padding: 8px 4px !important;
        }

        .ant-table-tbody > tr > td {
          &:nth-child(1) { // 申请时间
            width: 100px;
          }
          &:nth-child(2) { // 联系方式
            width: 80px;
          }
          &:nth-child(3) { // 返款方式
            width: 60px;
          }
          &:nth-child(4) { // 申请原因
            width: 120px;
          }
          &:nth-child(5) { // 状态
            width: 50px;
          }
        }
      }
    }

    .submit-section {
      margin-top: 20px;

      .ant-btn {
        height: 40px;
        font-size: 15px;
      }
    }
  }
}
</style>
